{% extends 'layout.html' %}
{% load static %}

{% block css %}
    <style>
        .chart-row {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-bottom: 20px;
        }

        .chart-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            position: relative;
        }

    </style>
{% endblock %}

{% block content %}
    <h1 style="text-align: center">热搜情感分析</h1>
    <div class="filter-bar">
        <select id="hotSelect" class="form-control" style="margin-bottom: 20px">
            <option value="">加载热榜...</option>
        </select>
    </div>

    <div class="chart-row">
        <div class="chart-container">
            <div id="clusterChart" style="height:400px"></div>
        </div>
        <div class="chart-container">
            <div id="sentimentPieChart" style="height:400px"></div>
        </div>
    </div>


    <div class="chart-container">
        <div id="sentimentScatterChart" style="height:500px"></div>
    </div>

{% endblock %}

{% block js %}
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
    <script>
        const COLORS = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE'];
        let charts = {
            cluster: echarts.init(document.getElementById('clusterChart')),
            sentimentPie: echarts.init(document.getElementById('sentimentPieChart')),
            sentimentScatter: echarts.init(document.getElementById('sentimentScatterChart'))
        };

        // 初始化热榜选择器
        async function initHotSelect() {
            try {
                const res = await fetch('/api/hot_boards/');
                const hots = await res.json();
                const select = document.getElementById('hotSelect');

                select.innerHTML = hots.map(hot =>
                    `<option value="${hot.id}">${hot.rank}. ${hot.keyword}</option>`
                ).join('');

                select.addEventListener('change', loadData);

                if (hots.length) {
                    select.value = hots[0].id;
                    setTimeout(() => loadData(), 300);
                }
            } catch (error) {
                console.error('加载热榜失败:', error);
                select.innerHTML = '<option value="">数据加载失败</option>';
            }
        }

        // 加载数据
        async function loadData() {
            const hotId = document.getElementById('hotSelect').value;
            if (!hotId) return;

            try {
                Object.values(charts).forEach(chart => chart.showLoading());

                // 同时获取聚类数据和情感数据
                const [clusterRes, sentimentRes] = await Promise.all([
                    fetch(`/api/cluster-data/?hot_board_id=${hotId}`),
                    fetch(`/api/sentiment-analysis/?hot_board_id=${hotId}`)
                ]);

                const clusterData = await clusterRes.json();
                const sentimentData = await sentimentRes.json();

                updateClusterChart(clusterData);
                updateSentimentPieChart(sentimentData);
                updateSentimentScatterChart(sentimentData.scatter_data); // 直接使用后端返回的散点数据
            } catch (error) {
                console.error('加载失败:', error);
            } finally {
                Object.values(charts).forEach(chart => chart.hideLoading());
            }
        }

        // 更新聚类图表
        function updateClusterChart(data) {
            const option = {
                title: {text: '主题聚类分析', left: 'center'},
                tooltip: {
                    formatter: function (params) {
                        return `聚类 ${params.data.label}<br>${params.data.text}`;
                    }
                },
                xAxis: {
                    type: 'value',
                    name: '主题'
                },
                yAxis: {
                    type: 'value',
                    name: '聚类'
                },
                series: [{
                    type: 'scatter',
                    data: data.map(point => ({
                        value: [point.x, point.y],
                        label: point.label,
                        text: point.text
                    })),
                    symbolSize: 10,
                    itemStyle: {
                        color: function (params) {
                            return COLORS[params.data.label % 5];
                        }
                    }
                }]
            };
            charts.cluster.setOption(option);
        }

        function updateSentimentPieChart(data) {
            const option = {
                title: {text: '情感分布', left: 'center'},
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [{
                    name: '情感分布',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        {value: data.positive, name: '积极'},
                        {value: data.negative, name: '消极'}
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            };
            charts.sentimentPie.setOption(option);
        }

        // 更新情感分析散点图
        function updateSentimentScatterChart(scatterData) {
            const option = {
                title: {
                    text: '情感分布散点图',
                    left: 'center',
                    subtext: '颜色代表情感倾向，点大小反映点赞量'  // 新增副标题说明
                },
                tooltip: {
                    // 修改提示内容为情感和点赞数
                    formatter: function (params) {
                        return `情感：${params.data.sentiment}<br>`
                            + `点赞：${params.data.likes}<br>`
                            + `坐标：(${params.value[0].toFixed(2)}, ${params.value[1].toFixed(2)})`;
                    }
                },
                xAxis: {
                    type: 'value',
                    name: '语义特征X',
                    min: 0,  // 明确坐标范围
                    max: 100,
                    axisLabel: {
                        color: '#666'  // 添加轴标签样式
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '情感强度Y',
                    min: 0,
                    max: 100,
                    axisLabel: {
                        color: '#666'
                    }
                },
                visualMap: {  // 新增视觉映射组件
                    show: false,
                    dimension: 2,  // 映射点赞数到点大小
                    min: 0,
                    max: 100,
                    inRange: {
                        symbolSize: [8, 30]  // 点赞数越大点越大
                    }
                },
                series: [{
                    type: 'scatter',
                    data: scatterData.map(point => ({
                        // 结构差异：直接使用x/y字段
                        value: [point.x, point.y, point.likes], // 第三维用于视觉映射
                        sentiment: point.sentiment,
                        likes: point.likes
                    })),
                    encode: {  // 关键配置！明确字段映射
                        x: 'x',
                        y: 'y',
                        tooltip: [0, 1, 2]  // 显示x,y,likes
                    },
                    symbolSize: function (val) {  // 动态大小
                        return Math.sqrt(val[2]) * 2;  // 根据点赞数计算大小
                    },
                    itemStyle: {
                        color: function (params) {  // 颜色映射差异
                            return {
                                '积极': '#91CC75',  // 绿色代表积极
                                '消极': '#EE6666'   // 红色代表消极
                            }[params.data.sentiment] || '#5470C6';  // 默认颜色
                        },
                        borderColor: 'rgba(255,255,255,0.8)',  // 添加白色边框
                        borderWidth: 1
                    },
                    emphasis: {  // 高亮样式
                        itemStyle: {
                            shadowBlur: 10,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }],
                legend: {  // 添加图例说明
                    data: ['积极', '消极'],
                    left: 'right',
                    itemStyle: {
                        color: ['#91CC75', '#EE6666']
                    }
                }
            };

            // 强制刷新图表（解决初次渲染问题）
            charts.sentimentScatter.setOption(option, true);
            setTimeout(() => charts.sentimentScatter.resize(), 0);
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            initHotSelect().then(() => {
                setTimeout(() => {
                    if (document.getElementById('hotSelect').value) {
                        loadData();
                    }
                }, 1000);
            });

            window.addEventListener('resize', () => {
                Object.values(charts).forEach(chart => chart.resize());
            });
        });
    </script>
{% endblock %}